class Solution {
    public int[][] merge(int[][] intervals) {
        if(intervals.length == 0) return new int[0][2];
        Arrays.sort(intervals,new Comparator<int[]>(){
            public int compare(int[] interval1,int[] interval2) {
                return interval1[0] - interval2[0];
            }
        });
        List<int[]> lists = new ArrayList<>();
        for(int i = 0;i < intervals.length;i++) {
            int l = intervals[i][0];
            int r = intervals[i][1];
            if(lists.size() == 0 || lists.get(lists.size()-1)[1] < l) {
                lists.add(new int[]{l,r});
            } else {
                lists.get(lists.size()-1)[1] = Math.max(lists.get(lists.size()-1)[1],r);
            }
        }
        return lists.toArray(new int[lists.size()][]);
    }
}